package com.by.http;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/8 19:44
 * @注释
 */
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class HttpRequest {
    private String method;
    private String uri;
    private Map<String, String> headers = new HashMap<>();
    private InputStream inputStream;

    public HttpRequest(InputStream inputStream) throws Exception {
        this.inputStream = inputStream;
        parseRequest();
    }

    private void parseRequest() throws Exception {
        // 解析请求行
        String line = readLine(inputStream);
        String[] parts = line.split(" ");
        method = parts[0];
        uri = parts[1];

        // 解析请求头
        while (true) {
            line = readLine(inputStream);
            if (line.isEmpty()) break;
            String[] headerParts = line.split(": ");
            headers.put(headerParts[0], headerParts[1]);
        }
    }

    private String readLine(InputStream inputStream) throws Exception {
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = inputStream.read()) != -1) {
            if (c == '\r') {
                inputStream.read(); // 跳过 \n
                break;
            }
            sb.append((char) c);
        }
        return sb.toString();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getHeader(String name) {
        return headers.get(name);
    }
}
